<?php

namespace Category;

use Content\ContentDAOModel;

/**
 * 分类业务相关
 */
class CategoryModel extends \Business\BusinessBase
{
    /**
     * 分类列表功能
     *
     * @param array $params
     * @return array
     */
    public function categoryList($params)
    {
        $page = empty($params['page']) ? 1 : $params['page'];
        $count = empty($params['count']) ? 10 : $params['count'];
        $where = empty($params['where']) ? null : $params['where'];
        $order = empty($params['order']) ? null : $params['order'];
        $baseUrl = empty($params['baseUrl']) ? null : $params['baseUrl'];

        // 取到总数
        $CategoryDAOModel = CategoryDAOModel::getInstance();
        $totalItemResult = $CategoryDAOModel->fetchAll(
            [new \Zend\Db\Sql\Expression('count(0) as total')], $where, null, 1
        );
        $totalItem = $totalItemResult[0]['total'];

        // 取到列表
        $paginator = new \Our\Paginator($page, $totalItem, $count, array('baseUrl' => $baseUrl, 'ext' => '/'));
        $result = $CategoryDAOModel->fetchAll(null, $where, $order, $count, ($page - 1) * $count);
        foreach ($result as &$item) {
            if ($item['parent_category_id']) {
                $category = $CategoryDAOModel->find($item['parent_category_id']);
                $item['parent_category_info'] = $category;
            }
            // 如果是父类，那么获取子类
            if ($item['parent_category_id'] == 0) {
                $item['child_category_list'] = $CategoryDAOModel->fetchAll(null,
                    ['parent_category_id' => $item['category_id']]);
            }
        }
        unset($item);

        return [$result, $paginator];
    }

    /**
     * 分类增加功能
     * @param $params
     *  category_name 分类名
     *  parent_category_id 分类id
     * @return int
     * @throws \Exception
     */
    public function add($params)
    {
        $CategoryDAOModel = CategoryDAOModel::getInstance();

        //判断分类是否已存在
        $result = $CategoryDAOModel->fetchAll(null, array("category_name" => $params['category_name']), null, 1);
        if ($result) {
            \Error\ErrorModel::throwException(11050);
        }
        $CategoryDAOModel->beginTransaction();
        $data = array(
            "category_name" => $params['category_name'],
            "parent_category_id" => $params['parent_category_id'],
            "add_time" => time(),
            "update_time" => time(),
        );
        $result = $CategoryDAOModel->insert($data);
        if (!$result) {
            $CategoryDAOModel->rollback();
            \Error\ErrorModel::throwException(11010);
        }
        $CategoryDAOModel->commit();
        return $result;
    }

    /**
     * 分类编辑功能
     *
     * @param array $params
     *  category_id 分类编号
     *  category_name 分类名
     *  parent_category_id 父类id
     * @return int
     * @throws \Exception
     */
    public function edit($params)
    {
        $CategoryDAOModel = CategoryDAOModel::getInstance();

        //判断分类是否已存在
        $result = $CategoryDAOModel->fetchAll(null, array("category_name" => $params['category_name'], "category_id<>?" => $params['category_id']), null, 1);
        if ($result) {
            \Error\ErrorModel::throwException(11050);
        }
        $CategoryDAOModel->beginTransaction();
        $data = array(
            "category_name" => $params['category_name'],
            "parent_category_id" => $params['parent_category_id'],
            "update_time" => time(),
        );
        $result = $CategoryDAOModel->update($data, array("category_id" => $params['category_id']));
        if (!$result) {
            $CategoryDAOModel->rollback();
            \Error\ErrorModel::throwException(11020);
        }
        $CategoryDAOModel->commit();
        return $result;
    }

    /**
     * 分类删除功能
     *
     * @param array $params
     *  category_id 分类编号
     * @return bool
     * @throws \Exception
     */
    public function delete($params)
    {
        $ContentDAOModel = ContentDAOModel::getInstance();
        $CategoryDAOModel = CategoryDAOModel::getInstance();

        // 检测该分类下是否有内容
        $contentList = $ContentDAOModel->fetchAll(null, array("category_id" => $params['category_id']), null, 1);
        if ($contentList) {
            \Error\ErrorModel::throwException(11031);
        }

        $CategoryDAOModel->beginTransaction();
        $result = $CategoryDAOModel->remove(array('category_id' => $params['category_id']));
        if (!$result) {
            $CategoryDAOModel->rollback();
            \Error\ErrorModel::throwException(11030);
        }
        $ContentDAOModel->commit();
        return true;
    }

    /**
     * 类实例
     *
     * @var \Category\CategoryModel
     */
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \Category\CategoryModel
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}
